import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Card,
    Row,
    Col,
    Input,
    Select,
    Button,
    Badge,
    Divider,
    Table,
    Modal,
    Tooltip,
    message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import AddOrUpdateElem from './components/AddOrUpdateElem';
import BatchUpdateElem from './components/BatchUpdateElem';
import { TableRowSelection } from 'antd/lib/table/interface';

const { Option } = Select;
const { Item } = Form;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
    dispatch: Dispatch;
    logisCenterChargeList: any;
    INITINFO: any;
    loading: boolean;
    screen: string;
}

interface TableListState {
    formValues: any;
    current: number;
    pageSize: number;
    statusVisible: boolean;
    statusInfo: {
        id: number;
        status: number;
    };
    editVisible: boolean;
    batchVisible: boolean;
    rowId: number;
    selectedRowKeys: React.Key[];
}

@connect(({
    logisCenterChargeList,
    common: { INITINFO },
    global: { screen },
    loading,
}: any) => ({
    logisCenterChargeList,
    INITINFO,
    screen,
    loading: loading.effects['logisCenterChargeList/fetch'],
}))

class TableListInfo extends Component<TableListProps, TableListState> {
    columns = [
        {
            title: '手机号',
            dataIndex: 'phone',
            width: 120,
            render: (text: string) => (
                <Tooltip title={text}>
                    <div className="wordOmit">{text}</div>
                </Tooltip>
            ),
        },
        {
            title: '校园小区',
            dataIndex: 'gardenName',
            width: 150,
            render: (text: string) => (
                <Tooltip title={text}>
                    <div className="wordOmit">{text}</div>
                </Tooltip>
            ),
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 80,
            render: (text: number) => (
                <Badge status={text ? 'processing' : 'error'} text={text ? '正常' : '禁用'} />
            ),
        },
        {
            title: '有效时间',
            width: 220,
            render: (text: any, record: any) => (
                <span>{record.startTime ? `${record.startTime}至${record.endTime}` : '--'}</span>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 180,
        },
        {
            title: '创建人',
            dataIndex: 'createUserName',
            width: 80,
            render: (text: string) => (
                <Tooltip title={text}>
                    <div className="wordOmit">{text}</div>
                </Tooltip>
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            width: 180,
        },
        {
            title: '操作人',
            dataIndex: 'updateUserName',
            width: 80,
            render: (text: string) => (
                <Tooltip title={text}>
                    <div className="wordOmit">{text}</div>
                </Tooltip>
            ),
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 120,
            render: (text: any, record: any) => (
                <div>
                    <span className="operLink" onClick={() => this.handleChangeEditModal(true, text)}>
                        编辑
                    </span>
                    <Divider type="vertical" />
                    <span className="operLink" onClick={() => this.handleChangeStatusModal(true, record)}>
                        {record.status ? '禁用' : '启用'}
                    </span>
                </div>
            ),
        },
    ];

    state: TableListState = {
        formValues: {},
        current: 1,
        pageSize: 20,
        statusVisible: false,
        statusInfo: {
            id: 0,
            status: 0,
        },
        editVisible: false,
        batchVisible: false,
        rowId: 0,
        selectedRowKeys: [],
    };

    static getDerivedStateFromProps(props: any, state: any) {
        const { search } = props.location;
        const query = qs.parse(search, { ignoreQueryPrefix: true });
        const { page, psize, ...formValues } = query;
        return {
            ...state,
            formValues,
            current: Number(page) || 1,
            pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
        };
    }

    componentDidMount() {
        this.setFieldsValue();
        this.fetchDataList();
        this.fetchGardenList();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { formValues, current, pageSize } = this.state;
        if (!_.isEqual(formValues, prevState.formValues)
            || current !== prevState.current
            || pageSize !== prevState.pageSize
        ) {
            this.setFieldsValue();
            this.fetchDataList();
        }
    }

    /** 设置表单值 */
    setFieldsValue = () => {
        const { formValues } = this.state;
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(formValues);
    };

    // 获取小园小区
    fetchGardenList = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'common/fetchGardenList' });
    };

    // 获取数据
    fetchDataList = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterChargeList/fetch',
            payload: this.getQueryParams(),
        });
    };

    // 获取查询参数
    getQueryParams = () => {
        const {
            formValues,
            current: pageIndex,
            pageSize = 20,
        } = this.state;
        const params = {
            ...formValues,
            pageIndex,
            pageSize,
        };

        return params;
    };

    handleChangeEditModal = (editVisible: boolean, id?: number) => {
        const { dispatch } = this.props;
        this.setState({ editVisible }, () => {
            if (id) {
                dispatch({
                    type: 'logisCenterChargeList/detail',
                    payload: { id },
                });
            } else {
                dispatch({ type: 'logisCenterChargeList/clearDetail' });
            }
        });
    };

    handleBatchChangeEditModal = (batchVisible: boolean, id?: number) => {
        const { dispatch } = this.props;
        if (!batchVisible) {
            this.setState({ selectedRowKeys: [] });
        }
        this.setState({ batchVisible }, () => {
            dispatch({ type: 'logisCenterChargeList/clearDetail' });
        });
    };

    /** 查询 */
    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        const { form: { validateFields } } = this.props;
        validateFields((errors, fieldsValue) => {
            if (errors) return;

            const query = {
                ...fieldsValue,
                page: 1,
                psize: 20,
            };

            const { dispatch } = this.props;
            addTab(dispatch, {
                name: '取件收费白名单',
                url: `${pathname}?${qs.stringify(query)}`,
                isTopMenu: true,
            });
        });
    };

    /** 重置 */
    handleReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '取件收费白名单',
            url: pathname,
            isTopMenu: true,
        });
    };

    /** 启用禁用Modal */
    handleChangeStatusModal = (statusVisible: boolean, record: any = {}) => {
        this.setState({
            statusVisible,
            statusInfo: {
                id: record.id,
                status: record.status ? 0 : 1,
            },
        });
    };

    /** 确认操作 */
    handleConfirm = () => {
        const { statusInfo } = this.state;
        const params = {
            search: this.getQueryParams(),
            ...statusInfo,
        };

        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterChargeList/status',
            payload: params,
        });

        this.handleChangeStatusModal(false);
    };

    /** 分页 */
    handleChangePage = (page: number, psize: number) => {
        const { formValues } = this.state;
        const query = {
            ...formValues,
            page,
            psize,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '取件收费白名单',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    renderSearchFormElem = () => {
        const {
            form: { getFieldDecorator },
            INITINFO: { gardenList },
        } = this.props;

        return (
            <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSearch}>
                <Card bordered={false} className="searchForm">
                    <Row gutter={12}>
                        <Col md={6} sm={24}>
                            <Item label="　手机号" colon={false}>
                                {getFieldDecorator('phone')(
                                    <Input allowClear type="number" placeholder="请输入" />,
                                )}
                            </Item>
                        </Col>
                        <Col md={6} sm={24}>
                            <Item label="校园小区" colon={false}>
                                {getFieldDecorator('gardenId')(
                                    <Select
                                        showSearch
                                        allowClear
                                        placeholder="请选择"
                                        filterOption={(input: any, option: any) => option.props.children
                                            .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {gardenList.map((item: any) => (
                                            <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                                        ))}
                                    </Select>,
                                )}
                            </Item>
                        </Col>
                        <Col md={12} sm={24}>
                            <div className="flexFeView">
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    className="smallButton"
                                >
                                    查询
                                </Button>
                                <Button
                                    type="primary"
                                    className="addButton smallButton marginL16"
                                    onClick={this.handleReset}
                                >
                                    重置
                                </Button>
                            </div>
                        </Col>
                    </Row>
                </Card>
            </Form>
        );
    };

    render() {
        const {
            current, pageSize, statusVisible, statusInfo, editVisible, batchVisible, selectedRowKeys } = this.state;

        const {
            logisCenterChargeList: { data },
            loading,
        }: any = this.props;

        const dataSource = data.list || [];
        const pagination: object = {
            total: data ? data.count : 0,
            current,
            pageSize,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showTotal: () => `共${data.count || 0}条数据`,
            onChange: this.handleChangePage,
            onShowSizeChange: this.handleChangePage,
        };

        const EditProps = {
            editVisible,
            changeModal: this.handleChangeEditModal.bind(this),
            searchInfo: this.getQueryParams(),
        };

        const BatchEditProps = {
            ids: selectedRowKeys,
            editVisible: batchVisible,
            changeModal: this.handleBatchChangeEditModal.bind(this),
            searchInfo: this.getQueryParams(),
        };

        const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
            // console.log('selectedRowKeys changed: ', newSelectedRowKeys, '---', this.state.selectedRowKeys);
            // this.setState({ selectedRowKeys: [...newSelectedRowKeys, ...this.state.selectedRowKeys] });
        };

        const onSelectRow = (record: any, selected: any, selectedRows: any, nativeEvent: any) => {
            const { selectedRowKeys } = this.state;
            const new_selectedRowKeys = [...selectedRowKeys];
            if (!selected) {
                const id = record.id;
                const index = new_selectedRowKeys.indexOf(id);
                new_selectedRowKeys.splice(index, 1);
            }
            else {
                new_selectedRowKeys.push(record.id);
            }
            this.setState({ selectedRowKeys: new_selectedRowKeys });
        };

        const onSelectAll = (selected: any, selectedRows: any, changeRows: any) => {
            const { selectedRowKeys } = this.state;
            const new_selectedRowKeys = [...selectedRowKeys];
            if (!selected) {
                for (let i = 0, len = changeRows.length; i < len; i++) {
                    const index = new_selectedRowKeys.indexOf(changeRows[i].id);
                    new_selectedRowKeys.splice(index, 1);
                }
            }
            else {
                for (let i = 0, len = changeRows.length; i < len; i++) {
                    new_selectedRowKeys.push(changeRows[i].id);
                }
            }
            this.setState({ selectedRowKeys: new_selectedRowKeys });
        }

        const rowSelection: TableRowSelection<any> = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: onSelectChange,
            onSelect: onSelectRow,
            onSelectAll: onSelectAll,
        };

        return (
            <>
                <PageHeader />

                {this.renderSearchFormElem()}

                <Card bordered={false} className="tableList">
                    <div className="tableBtns">
                        <Button
                            type="primary"
                            size="small"
                            className="smallButton"
                            onClick={() => this.handleChangeEditModal(true)}
                        >
                            新建
                        </Button>
                        <Button
                            type="primary"
                            size="small"
                            className="smallButton marginL16"
                            onClick={() => {
                                console.log('selectedRowKeys', selectedRowKeys);
                                if (selectedRowKeys.length > 0) {
                                    this.handleBatchChangeEditModal(true)
                                }
                                else {
                                    message.warning('请至少选择一个白名单')
                                }
                            }}
                        >
                            批量编辑
                        </Button>
                    </div>
                    <Table
                        rowKey="id"
                        tableLayout="fixed"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={dataSource}
                        rowSelection={rowSelection}
                        pagination={pagination}
                        loading={loading}
                        scroll={{ x: 980 }}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />
                </Card>

                <Modal
                    title="确认提示"
                    visible={statusVisible}
                    destroyOnClose
                    okText={statusInfo.status ? '启用' : '禁用'}
                    onOk={this.handleConfirm}
                    onCancel={() => this.handleChangeStatusModal(false)}
                >
                    <p style={{ textAlign: 'center' }}>确定{statusInfo.status ? '启用' : '禁用'}吗?</p>
                </Modal>

                <AddOrUpdateElem {...EditProps} />
                <BatchUpdateElem {...BatchEditProps} />
            </>
        );
    }
}

export default Form.create<TableListProps>()(TableListInfo);
